﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using STX.Admin.Models.BizActivity;
using STX.Service;
using STX.Domain;
using STX.Web.Framework;
using STX.Web.Framework.Security;

namespace STX.Admin.Controllers
{
    public class BizActivityController : BasePages1Controller<BizActivity, IndexModel, AddModel, EditModel, QueryModel>
    {
        public BizAreaService BizAreaService { get; set; }
        public BizActivityService BizActivityService { get; set; }
        public BizMaterialCategoryService BizMaterialCategoryService { get; set; }
        public BizQuotePriceTemplateService BizQuotePriceTemplateService { get; set; }
        public BizQuotePriceService BizQuotePriceService { get; set; }
        public BizProjectService BizProjectService { get; set; }
        public BizSupplierService BizSupplierService { get; set; }
        public TabAdministratorService TabAdministratorService { get; set; }
        public BizActivityItemService BizActivityItemService { get; set; }
        public BizActivityItemSupplierService BizActivityItemSupplierService { get; set; }

        #region 初始化

        protected override void OnInit(out Func<BaseService<BizActivity>> thisService,
            out Func<IndexModel> getIndexModelFunc, out Func<AddModel> getAddModelFunc,
            out Func<int, EditModel> getEditModelFunc)
        {
            thisService = () => BizActivityService;
            getIndexModelFunc = () =>
            {
                var areas = BizAreaService.FindAll();
                return new IndexModel
                {
                    Areas = new SelectList(areas, "Id", "Name"),
                };

            };
            getAddModelFunc = () => new AddModel
            {
                MaterialCategories = BizMaterialCategoryService.FindAll().ToList(),
                Areas = BizAreaService.FindAll().ToList()
            };
            getEditModelFunc = id =>
            {
                var model = BizActivityService.FindModelById(id);
                if (model == null)
                {
                    throw new Exception("此数据可能已被删除");
                }
                return new EditModel
                {
                    Id = id,
                    //MainAreaId = model.MainAreaId,
                    ProjectId = model.ProjectId,
                    ProjectName = model.BizProject.Name,
                    StartTime = model.StartTime,
                    EndTime = model.EndTime,
                    Place = model.Place,
                    BizActivityItems = model.BizActivityItems,
                    MaterialCategories = BizMaterialCategoryService.FindAll().ToList(),
                    Name = model.Name,
                    Executor = model.Executor,
                    Planner = model.Planner,
                    Driver = model.Driver,
                    ResponsiblePerson = model.ResponsiblePerson,
                    Step = model.Step,
                    Auditing = model.Auditing
                };
            };
        }

        #endregion

        #region Methods 方法
        protected override long AddHandler(AddModel addModel)
        {
            throw new NotImplementedException();
        }

        protected override bool EditHandler(EditModel editModel)
        {
            throw new NotImplementedException();
        }

        protected override IQueryable<BizActivity> QueryHandler(QueryModel queryModel, IQueryable<BizActivity> queryable)
        {
            if (AdminContext.CurrentUser.Position == PositionEnum.Salesperson)
            {
                queryable = queryable.Where(o => o.AdministratorId == AdminContext.CurrentUser.Id);
            }
            if (AdminContext.CurrentUser.Position == PositionEnum.ProjectManager)
            {
                queryable = queryable.Where(o => (o.Step == StepEnum.制作报价 
                    && o.Step == StepEnum.制作成本 
                    && o.AdministratorId == AdminContext.CurrentUser.Id) 
                    || o.Step== StepEnum.项目经理审核报价
                    || o.Step == StepEnum.项目总监审核报价
                    || o.Step == StepEnum.项目总监审核成本
                    || o.Step == StepEnum.财务经理审核成本
                    || o.Step == StepEnum.财务总监审核成本
                    || o.Step == StepEnum.总经理审核成本);
            }
            if (queryModel.AreaId > 0)
                queryable = queryable.Where(o => o.BizProject.AreaId == queryModel.AreaId);
            if (!queryModel.Name.IsNullOrEmpty())
                queryable = queryable.Where(o => o.Name.Contains(queryModel.Name));
            return queryable;
            return queryable;
        }
        #endregion

        #region 扩展方法

        /// <summary>
        /// 获取某地方下的项目
        /// </summary>
        /// <param name="areaId"></param>
        /// <returns></returns>
        public JsonResult GetProjectsByAreaId(int areaId)
        {

            var query = BizProjectService.FindAll().Where(o=>o.AreaId==areaId);
            var list = new List<dynamic>();
            foreach (var project in query)
            {
                list.Add(new
                {
                    Id = project.Id,
                    Name = project.Name
                });
            }
            return !list.Any()
                ? new JsonResult {Data = new {success = false}}
                : new JsonResult {Data = new {success = true, list = list}};
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="areaId"></param>
        /// <returns></returns>
        public JsonResult GetQuotePriceTemplateData(string key, int areaId)
        {
            int intKey = 0;
            int.TryParse(key, out intKey);

            var sql = string.Format(@"SELECT TOP 10 Id, MaterialCategoryId, Name, Unit, Required, ProjectCostPrice, FinanceCostPrice, Status, Code, AreaId,Split
                       FROM Biz.QuotePriceTemplate 
                       WHERE (CHARINDEX(@key,[Name])>0 OR CHARINDEX(@key,dbo.fun_getPY([Name]))>0) 
                             AND AreaId=@areaId");
            if (intKey > 0)
            {
                sql =
                    string.Format(@"SELECT TOP 10 Id, MaterialCategoryId, Name, Unit, Required, ProjectCostPrice, FinanceCostPrice, Status, Code, AreaId,Split
                       FROM Biz.QuotePriceTemplate 
                       WHERE [Code] LIKE '{0}%' AND [AreaId]=@areaId ORDER BY LEN(Code) ASC, Code ASC", intKey);
            }
            var parameters = new SqlParameter[]
            {
                new SqlParameter("@key", key),
                new SqlParameter("@areaId", areaId),
            };

            var query = BizQuotePriceTemplateService.FindAll(sql, parameters);
            var tpData = query.ToList();
            if (!tpData.Any()) return new JsonResult { Data = new { success = false} };
            var result = tpData.Select(template => new tempClass
            {
                Name = template.Name, 
                Required = template.Required, 
                TpCode = template.Code, 
                Unit = template.Unit,
                QuotePrices = new List<dynamic>()
            });
            var tempClasses = result as tempClass[] ?? result.ToArray();
            foreach (var item in tempClasses)
            {
                var tp = tpData.FirstOrDefault(o => o.Code.Trim() == item.TpCode.Trim());

                if (tp != null)
                    foreach (var price in tp.BizQuotePriceList)
                    {
                        item.QuotePrices.Add(new
                        {
                            Id = price.Id,
                            StartNum = price.StartNum,
                            EndNum = price.EndNum,
                            QuotePrice = price.QuotePrice
                        });
                    }
            }

            return new JsonResult {Data = new {success = true, list = tempClasses}};
        }

        class tempClass
        {
            public string Name { get; set; }
            public string Unit { get; set; }
            public string Required { get; set; }
            public string TpCode { get; set; }
            public List<dynamic> QuotePrices { get; set; }
        }
        #endregion

        #region 报价

        #region 制作报价
        /// <summary>
        /// 制作报价
        /// </summary>
        /// <returns></returns>
        public ActionResult AddQuote()
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作报价))
            {
                throw new Exception("你没有权限制作报价");
            }
            var dto = new AddQuoteModel
            {
                MaterialCategories = BizMaterialCategoryService.FindAll().OrderBy(o=>o.Code).ToList(),
                Areas = TabAdministratorService.FindModelById(AdminContext.CurrentUser.Id).Areas.ToList()
            };
            return View(dto);
            //todo 必须将执行调出来，供前台使用
        }

        public JsonResult SaveAddQuote(AddQuoteModel dto)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作报价))
            {
                throw new Exception("你没有权限制作报价");
            }
            var model = new BizActivity
            {
                AdministratorId = AdminContext.CurrentUser.Id,
                CostGeneratedTime = DateTime.Now,
                CostTabulator = "",
                Driver = dto.Driver,
                EndTime = dto.EndTime,
                Executor = dto.Executor,
                Name = dto.Name,
                Place = dto.Place,
                Planner = dto.Planner,
                ProjectId = dto.ProjectId,
                QuotationGeneratedTime = DateTime.Now,
                QuotationTabulator = AdminContext.CurrentUser.Name,
                ResponsiblePerson = dto.ResponsiblePerson,
                StartTime = dto.StartTime,
                TimeDetail = dto.TimeDetail,
                BizActivityItems = new List<BizActivityItem>()
            };
            foreach (var activityItem in dto.BizActivityItems)
            {
                if (activityItem.Name.IsNullOrEmpty()) continue;
                var activityItemModel = new BizActivityItem();
                activityItemModel.TpCode = activityItem.TpCode;
                activityItemModel.Require = activityItem.Require;
                activityItemModel.Numb = activityItem.Numb;
                activityItemModel.MaterialBelong = activityItem.MaterialBelong;
                activityItemModel.MaterialForm = activityItem.MaterialForm;
                activityItemModel.MaterialCategoryId = activityItem.MaterialCategoryId;

                activityItemModel.Name = activityItem.Name;
                activityItemModel.Unit = activityItem.Unit;
                activityItemModel.QuotationPrice = activityItem.QuotationPrice;

                if (!activityItem.TpCode.IsNullOrEmpty())
                {
                    var tpEntity = BizQuotePriceTemplateService.FindAll()
                        .FirstOrDefault(o => o.Code.Trim() == activityItem.TpCode.Trim());
                    
                    if (tpEntity != null)
                    {
                        activityItemModel.Name = tpEntity.Name;
                        activityItemModel.Unit = tpEntity.Unit;
                        activityItemModel.ProjectCostPrice = tpEntity.ProjectCostPrice;
                        activityItemModel.FinanceCostPrice = tpEntity.FinanceCostPrice;
                        var priceEntity = tpEntity.BizQuotePriceList
                            .FirstOrDefault(o => o.StartNum <= activityItem.Numb && o.EndNum >= activityItem.Numb);
                        if (priceEntity != null)
                        {
                            activityItemModel.QuotationPrice = priceEntity.QuotePrice; 
                        }
                    }
                }
                model.BizActivityItems.Add(activityItemModel);
            }
            model.Step = StepEnum.制作报价;
            ModifyStep(model, dto.UserBehave,dto.Comment);
            var id = BizActivityService.Add(model);
            return id > 0
                ? new JsonResult {Data = new {success = true}}
                : new JsonResult {Data = new {success = false}};
        }
        #endregion

        #region 编辑/审核报价
        public ActionResult EditQuote(int id)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作报价 | RightsEnum.审核报价))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            var dto = new EditQuoteModel
            {
                Id=model.Id,
                ProjectId = model.ProjectId,
                AreaId = model.BizProject.AreaId,
                MaterialCategories = BizMaterialCategoryService.FindAll().OrderBy(o => o.Code).ToList(),
                Name = model.Name,
                ProjectName = model.BizProject.Name,
                StartTime = model.StartTime,
                EndTime = model.EndTime,
                TimeDetail = model.TimeDetail,
                Place = model.Place,
                QuotationTabulator = model.QuotationTabulator,
                QuotationGeneratedTime = model.QuotationGeneratedTime,
                Executor = model.Executor,
                ResponsiblePerson = model.ResponsiblePerson,
                Planner = model.Planner,
                Driver = model.Driver,
                BizActivityItems = model.BizActivityItems,
                Step = model.Step,
                Comment = model.Comment
            };
            return View(dto);
        }
        #endregion

        #region 保存报价

        public JsonResult SaveEditQuote(EditQuoteModel dto)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作报价 | RightsEnum.审核报价))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(dto.Id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            model.Name = dto.Name;
            model.StartTime = dto.StartTime;
            model.EndTime = dto.EndTime;
            model.TimeDetail = dto.TimeDetail;
            model.Place = dto.Place;
            model.Executor = dto.Executor;
            model.ResponsiblePerson = dto.ResponsiblePerson;
            model.Planner = dto.Planner;
            model.Driver = dto.Driver;

            BizActivityItemService.RemoveIds(model.BizActivityItems.Select(o => o.Id).ToArray());

            var list = new List<BizActivityItem>();
            foreach (var activityItem in dto.BizActivityItems)
            {
                if (activityItem.Name.IsNullOrEmpty()) continue;
                var activityItemModel = new BizActivityItem();
                activityItemModel.TpCode = activityItem.TpCode;
                activityItemModel.Require = activityItem.Require;
                activityItemModel.Numb = activityItem.Numb;
                activityItemModel.MaterialBelong = activityItem.MaterialBelong;
                activityItemModel.MaterialForm = activityItem.MaterialForm;
                activityItemModel.MaterialCategoryId = activityItem.MaterialCategoryId;

                activityItemModel.Name = activityItem.Name;
                activityItemModel.Unit = activityItem.Unit;
                activityItemModel.QuotationPrice = activityItem.QuotationPrice;

                if (!activityItem.TpCode.IsNullOrEmpty())
                {
                    var tpEntity = BizQuotePriceTemplateService.FindAll()
                        .FirstOrDefault(o => o.Code.Trim() == activityItem.TpCode.Trim());

                    if (tpEntity != null)
                    {
                        activityItemModel.Name = tpEntity.Name;
                        activityItemModel.Unit = tpEntity.Unit;
                        activityItemModel.ProjectCostPrice = tpEntity.ProjectCostPrice;
                        activityItemModel.FinanceCostPrice = tpEntity.FinanceCostPrice;

                        var priceEntity = tpEntity.BizQuotePriceList
                            .FirstOrDefault(o => o.StartNum <= activityItem.Numb && o.EndNum >= activityItem.Numb);
                        if (priceEntity != null)
                        {
                            activityItemModel.QuotationPrice = priceEntity.QuotePrice;
                        }
                    }
                }
                list.Add(activityItemModel);
            }
            model.BizActivityItems = list;
            ModifyStep(model, dto.UserBehave, dto.Comment);
            var isupdated = BizActivityService.Update(model);
            return isupdated
                ? new JsonResult {Data = new {success = true}}
                : new JsonResult {Data = new {success = false}};
        }

        #endregion

        #region 审核报价
        public JsonResult SaveAuditQuote(EditQuoteModel dto)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作报价 | RightsEnum.审核报价))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(dto.Id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            if (dto.UserBehave == UserBehave.审核失败)
            {
                model.Step = dto.Step;
            }
            foreach (var item in model.BizActivityItems)
            {
                var dtoActivityItem = dto.BizActivityItems.FirstOrDefault(o => o.Id == item.Id);
                if (dtoActivityItem == null) continue;
                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Correct)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.None;
                }
                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.None
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.Error;
                }
            }
            ModifyStep(model, dto.UserBehave,dto.Comment);
            var isupdated = BizActivityService.Update(model);
            return isupdated
                ? new JsonResult { Data = new { success = true } }
                : new JsonResult { Data = new { success = false } };
        }
        #endregion

        #region 撤回报价
        /// <summary>
        /// 撤回报价
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult WithdrawQuote(int id)
        {
            var model = BizActivityService.FindModelById(id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            model.Step = StepEnum.制作报价;
            model.Auditing= AuditingEnum.草稿;
            var isupdated = BizActivityService.Update(model);
            return isupdated
                ? new JsonResult { Data = new { success = true } }
                : new JsonResult { Data = new { success = false } };
        }

        #endregion
        #endregion

        #region 成本

        public ActionResult EditCost(int id)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作项目成本 | RightsEnum.审核项目成本))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            var dto = new EditCostModel
            {
                Id = model.Id,
                ProjectId = model.ProjectId,
                AreaId = model.BizProject.AreaId,
                MaterialCategories = BizMaterialCategoryService.FindAll().OrderBy(o => o.Code).ToList(),
                Name = model.Name,
                ProjectName = model.BizProject.Name,
                StartTime = model.StartTime,
                EndTime = model.EndTime,
                TimeDetail = model.TimeDetail,
                Place = model.Place,
                QuotationTabulator = model.QuotationTabulator,
                QuotationGeneratedTime = model.QuotationGeneratedTime,
                Executor = model.Executor,
                ResponsiblePerson = model.ResponsiblePerson,
                Planner = model.Planner,
                Driver = model.Driver,
                BizActivityItems = model.BizActivityItems,
                Step = model.Step,
                TemplateQuotePrices = BizQuotePriceTemplateService.FindAll().ToList(),
                BizActivityItemSuppliers = BizActivityItemSupplierService.FindAll(),
                Comment = model.Comment
            };
            return View(dto);
        }

        public JsonResult SaveEditCost(EditCostModel dto)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作项目成本 | RightsEnum.审核项目成本))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(dto.Id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            if (dto.UserBehave == UserBehave.审核失败)
            {
                model.Step = dto.Step;
            }
            foreach (var item in model.BizActivityItems)
            {
                var dtoActivityItem = dto.BizActivityItems.FirstOrDefault(o => o.Id == item.Id);
                if (dtoActivityItem == null) continue;
                if (dto.UserBehave == UserBehave.保存为草稿)
                {
                    item.ProjectCostPrice = dtoActivityItem.ProjectCostPrice;
                    item.SupplierName = dtoActivityItem.SupplierName;
                    if (!dtoActivityItem.SupplierIds.IsEmpty())
                    {
                        var list = new List<BizActivityItemSupplier>();
                        foreach (var supplierId in dtoActivityItem.SupplierIds)
                        {
                            var supplierEntity = BizSupplierService.FindModelById(supplierId);
                            list.Add(new BizActivityItemSupplier
                            {
                                ActivityItemId = item.Id,
                                Numb = 0,
                                SupplierId = supplierEntity.Id
                            });
                        }
                        BizActivityItemSupplierService.RemoveIds(
                            item.BizActivityItemSuppliers.Select(o => o.Id).ToArray());
                        item.BizActivityItemSuppliers = list;
                    }
                }
                if (dto.UserBehave == UserBehave.提交审核)
                {
                    var tpEntity = BizQuotePriceTemplateService.FindAll().FirstOrDefault(o => o.Code == item.TpCode);
                    if (tpEntity != null)
                    {
                        item.ProjectCostPrice = tpEntity.ProjectCostPrice;
                        item.FinanceCostPrice = tpEntity.ProjectCostPrice;
                    }
                    else
                    {
                        item.ProjectCostPrice = dtoActivityItem.ProjectCostPrice;
                        item.FinanceCostPrice = dtoActivityItem.ProjectCostPrice;
                    }
                    if (!dtoActivityItem.SupplierIds.IsEmpty())
                    {
                        var list = new List<BizActivityItemSupplier>();
                        foreach (var supplierId in dtoActivityItem.SupplierIds)
                        {
                            var supplierEntity = BizSupplierService.FindModelById(supplierId);
                            list.Add(new BizActivityItemSupplier
                            {
                                ActivityItemId = item.Id,
                                Numb = 0,
                                SupplierId = supplierEntity.Id
                            });
                        }
                        BizActivityItemSupplierService.RemoveIds(
                            item.BizActivityItemSuppliers.Select(o => o.Id).ToArray());
                        item.BizActivityItemSuppliers = list;
                    }
                    else
                    {
                        if (dtoActivityItem.SupplierName.IsNullOrEmpty())
                        {
                            throw new Exception("必须选择供应商，如果没有则手动录入一个");
                        }

                        var tpCode = DateTime.Now.ToString("yyMMddhhmmssfff");
                        var tpId = BizQuotePriceTemplateService.Add(new BizQuotePriceTemplate
                        {
                            AreaId = dto.AreaId,
                            Code = tpCode,
                            FinanceCostPrice = dtoActivityItem.ProjectCostPrice,
                            ProjectCostPrice = dtoActivityItem.ProjectCostPrice,
                            Name = item.Name,
                            Unit = item.Unit,
                            MaterialCategoryId = item.MaterialCategoryId,
                            Required = item.Require,
                            BizQuotePriceList = new List<BizQuotePrice>()
                            {
                                new BizQuotePrice()
                                {
                                    StartNum = 1,
                                    EndNum = 99999,
                                    QuotePrice = item.QuotationPrice
                                }
                            },
                            Status = StatusEnum.Open,
                            Split = BizQuotePriceTemplate.SplitEnum.NoSplit
                            
                        });

                        var mySupplierId = (int)BizSupplierService.Add(new BizSupplier()
                        {
                            AreaId = dto.AreaId,
                            Auditing = BizSupplier.SupplierAuditingEnum.NoAudited,
                            Name = dtoActivityItem.SupplierName,
                            QuotePriceTemplates = BizQuotePriceTemplateService.FindAll().Where(o=>o.Id==tpId).ToList()
                        });

                        item.TpCode = tpCode;

                        BizActivityItemSupplierService.RemoveIds(
                            item.BizActivityItemSuppliers.Select(o => o.Id).ToArray());
                        item.BizActivityItemSuppliers = new List<BizActivityItemSupplier>()
                        {
                            new BizActivityItemSupplier
                            {
                                ActivityItemId = item.Id,
                                Numb = 0,
                                SupplierId = mySupplierId
                            }
                        };
                    }
                }


                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Correct)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.None;
                }
                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.None
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.Error;
                }
            }
            ModifyStep(model, dto.UserBehave,dto.Comment);
            var isupdated = BizActivityService.Update(model);
            return isupdated
                ? new JsonResult { Data = new { success = true } }
                : new JsonResult { Data = new { success = false } };
        }

        public JsonResult SaveAuditCost(EditCostModel dto)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作项目成本 | RightsEnum.审核项目成本))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(dto.Id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            if (dto.UserBehave == UserBehave.审核失败)
            {
                model.Step = dto.Step;
            }
            foreach (var item in model.BizActivityItems)
            {
                var dtoActivityItem = dto.BizActivityItems.FirstOrDefault(o => o.Id == item.Id);
                if (dtoActivityItem == null) continue;
                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Correct)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.None;
                }
                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.None
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.Error;
                }
            }
            ModifyStep(model, dto.UserBehave, dto.Comment);
            var isupdated = BizActivityService.Update(model);
            return isupdated
                ? new JsonResult { Data = new { success = true } }
                : new JsonResult { Data = new { success = false } };
        }

        #endregion

        #region 财务成本

        public ActionResult EditFinance(int id)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作财务成本 | RightsEnum.审核财务成本))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            var dto = new EditCostModel
            {
                Id = model.Id,
                ProjectId = model.ProjectId,
                AreaId = model.BizProject.AreaId,
                MaterialCategories = BizMaterialCategoryService.FindAll().OrderBy(o => o.Code).ToList(),
                Name = model.Name,
                ProjectName = model.BizProject.Name,
                StartTime = model.StartTime,
                EndTime = model.EndTime,
                TimeDetail = model.TimeDetail,
                Place = model.Place,
                QuotationTabulator = model.QuotationTabulator,
                QuotationGeneratedTime = model.QuotationGeneratedTime,
                Executor = model.Executor,
                ResponsiblePerson = model.ResponsiblePerson,
                Planner = model.Planner,
                Driver = model.Driver,
                BizActivityItems = model.BizActivityItems,
                Step = model.Step,
                TemplateQuotePrices = BizQuotePriceTemplateService.FindAll().ToList(),
                BizActivityItemSuppliers = BizActivityItemSupplierService.FindAll(),
                Comment = model.Comment
            };
            return View(dto);
        }

        public JsonResult SaveEditFinance(EditCostModel dto)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作财务成本 | RightsEnum.审核财务成本))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(dto.Id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            if (dto.UserBehave == UserBehave.审核失败)
            {
                model.Step = dto.Step;
            }
            foreach (var item in model.BizActivityItems)
            {
                var dtoActivityItem = dto.BizActivityItems.FirstOrDefault(o => o.Id == item.Id);
                //if (dtoActivityItem == null) continue;
                item.FinanceCostPrice = dtoActivityItem.FinanceCostPrice;


                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Correct)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.None;
                }
                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.None
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.Error;
                }
            }
            ModifyStep(model, dto.UserBehave,dto.Comment);
            var isupdated = BizActivityService.Update(model);
            return isupdated
                ? new JsonResult { Data = new { success = true } }
                : new JsonResult { Data = new { success = false } };
        }

        public JsonResult SaveAuditFinance(EditCostModel dto)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.审核财务成本))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(dto.Id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            if (dto.UserBehave == UserBehave.审核失败)
            {
                model.Step = dto.Step;
            }
            foreach (var item in model.BizActivityItems)
            {
                var dtoActivityItem = dto.BizActivityItems.FirstOrDefault(o => o.Id == item.Id);
                if (dtoActivityItem == null) continue;

                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Correct)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.None;
                }
                if (item.ErrorStatus == BizActivityItem.ErrorStatusEnum.None
                    && dtoActivityItem.ErrorStatus == BizActivityItem.ErrorStatusEnum.Error)
                {
                    item.ErrorStatus = BizActivityItem.ErrorStatusEnum.Error;
                }
            }
            ModifyStep(model, dto.UserBehave,dto.Comment);
            var isupdated = BizActivityService.Update(model);
            return isupdated
                ? new JsonResult { Data = new { success = true } }
                : new JsonResult { Data = new { success = false } };
        }
        #endregion

        #region 打印
        #region 打印报价

        public ActionResult PrintQuotePrice(int id)
        {
            ViewBag.PrintId = id;
            return View();
        }

        #endregion

        #region 打印成本

        public ActionResult PrintCost(int id)
        {
            ViewBag.PrintId = id;
            return View();
        }
        #endregion

        #endregion

        #region 财务部分
        #region 活动明细台账
        public ActionResult ActivityDetailAccount(int id)
        {
            if (!AdminContext.CurrentUser.Position.CheckRights(RightsEnum.制作财务成本 | RightsEnum.审核财务成本))
            {
                throw new Exception("无权限");
            }
            var model = BizActivityService.FindModelById(id);
            if (model == null)
            {
                throw new Exception("此条数据可能已被删除或失效");
            }
            var dto = new EditCostModel
            {
                Id = model.Id,
                ProjectId = model.ProjectId,
                AreaId = model.BizProject.AreaId,
                MaterialCategories = BizMaterialCategoryService.FindAll().ToList(),
                Name = model.Name,
                ProjectName = model.BizProject.Name,
                StartTime = model.StartTime,
                EndTime = model.EndTime,
                TimeDetail = model.TimeDetail,
                Place = model.Place,
                QuotationTabulator = model.QuotationTabulator,
                QuotationGeneratedTime = model.QuotationGeneratedTime,
                Executor = model.Executor,
                ResponsiblePerson = model.ResponsiblePerson,
                Planner = model.Planner,
                Driver = model.Driver,
                BizActivityItems = model.BizActivityItems,
                Step = model.Step,
                TemplateQuotePrices = BizQuotePriceTemplateService.FindAll().ToList(),
                Comment = model.Comment
            };
            return View(dto);
        }
        #endregion

        #endregion

        public BizActivity ModifyStep(BizActivity model,UserBehave behave,string comment)
        {
            if (behave == UserBehave.保存为草稿)
            {
                model.Comment = "";
                model.Auditing = AuditingEnum.草稿;
            }

            var fieldInfo = model.Step.GetType().GetField(model.Step.ToString());
            var cas = (StepAttribute[]) fieldInfo.GetCustomAttributes(typeof (StepAttribute), false);
            if (cas.Length <= 0)
            {
                throw new Exception("流程步骤配置出了问题");
            }

            if (behave == UserBehave.提交审核)
            {
                model.Step = cas[0].NextStep;
                model.Comment = "";
                model.Auditing = AuditingEnum.待审核;
            }

            if (behave == UserBehave.审核失败)
            {
                model.Comment = comment;
                model.Auditing = AuditingEnum.审核失败;
            }

            if (behave == UserBehave.审核成功)
            {
                model.Comment = "";
                if (model.Step == cas[0].NextStep)
                {
                    model.Auditing = AuditingEnum.审核成功;
                }
                else
                {
                    model.Step = cas[0].NextStep;
                    model.Auditing = AuditingEnum.待审核;
                }
            }
            return model;
        }

        public ActionResult Auditing()
        {
            return View();
        }

        
    }
}
